package com.ewins.weatherdataclient.ui;

import com.ewins.weatherdataclient.common.Constant;
import com.ewins.weatherdataclient.https.HttpsDefault;
import com.ewins.weatherdataclient.interfacedatamodule.InterfaceDataManagerHttp;
import com.ewins.weatherdatautils.bean.DownLoadFile;
import com.ewins.weatherdatautils.bean.PathNode;
import com.ewins.weatherdatautils.utils.Configuration;
import com.ewins.weatherdatautils.utils.Traversal;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;

/**
 * Created by anzilu on 2016/1/28.
 */
public class DownloadConfig extends Stage{

    CheckBoxTreeItem<String> rootItem=new CheckBoxTreeItem<String>();
    VBox ruleBox=new VBox();
    Label topic=new Label("过滤规则(使用逗号分隔的文件扩展名)");
    TextField rule=new TextField();
    HBox buttonBox=new HBox();
    VBox renameBox=new VBox();
    CheckBox rename=new CheckBox("去掉随机时间");
    Button edit=new Button("编辑");
    Button save=new Button("保存");
    RadioButton selectAll=new RadioButton("全选");
    RadioButton deselectAll=new RadioButton("全不选");
    Button dltoLabel=new Button("选择下载保存目录");
    TextField downloadto=new TextField();
    Button download= new Button("下载");
    Button cancel=new Button("取消");
    HashMap<CheckBoxTreeItem,PathNode> record=new HashMap<CheckBoxTreeItem, PathNode>();
    ArrayList<PathNode> policy=new ArrayList<PathNode>();
    public PathNode hierarchy;
    CheckBoxTreeItem<String> focusItem;
    Stage stage = new Stage();
    Logger log= Logger.getLogger(DownloadConfig.class);

    public static void main(String[] args) {
        //launch(args);
        DownloadConfig dc=new DownloadConfig();
    }

    public DownloadConfig() {
    //public void DownloadConfig(Stage stg) {

        record.clear();
        //Initialize the Stage with type of modal
        setTitle("新建下载");

        //test-create a test hierarchy for use
        //should be replaced by real directory list
//        PathNode pathNode=new PathNode("D:\\adcc");
//        PathNode pn= Traversal.createJsonPath(pathNode);
//
//        JSONObject jo=JSONObject.fromObject(pn);


//        String hierarchies=jo.toString();
        String filePath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "config.properties";
        String url= Configuration.GetValueByKey(filePath, "HierarchyUrl");
        String hierarchies=getjsonFromUrl(url);
        JSONObject jsonObject= JSONObject.fromObject(hierarchies);
        PathNode retrievement=Traversal.retrievePathNode(jsonObject.getJSONObject("root"));

        rootItem.setExpanded(true);

        createTree(rootItem, retrievement);
        final TreeView<String> tree = new TreeView<String> ();
        tree.setRoot(rootItem);
        tree.setCellFactory(CheckBoxTreeCell.<String>forTreeView());
        tree.getFocusModel().focusedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
            @Override
            public void changed(ObservableValue<? extends TreeItem<String>> observableValue, TreeItem<String> stringTreeItem, TreeItem<String> t1) {

                if (t1 != null) {
                    focusItem = (CheckBoxTreeItem<String>) t1;
                    PathNode pn = record.get(focusItem);
                    if (null != pn) {
                        if (focusItem.isLeaf()) {
                            rule.clear();
                            setRuleBoxStatus(true);
                            rule.setText(pn.getRule());
                            rename.setSelected(false);
                            renameBox.setDisable(true);

                        } else {
                            setRuleBoxStatus(false);
                            if (pn.getPath().endsWith("RADR_LATION_OUT")) {
                                renameBox.setDisable(false);
                                if (pn.isRename()) {
                                    rename.setSelected(true);
                                } else {
                                    rename.setSelected(false);
                                }
                            } else {
                                rename.setSelected(false);
                                renameBox.setDisable(true);
                            }
                        }
                    }
                }
            }
        });
        dltoLabel.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final DirectoryChooser directoryChooser=new DirectoryChooser();
                final File selectedDirectory = directoryChooser.showDialog(stage);
                if (selectedDirectory != null) {
                    downloadto.setText(selectedDirectory.getAbsolutePath());
                }
            }
        });
        edit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                rule.setEditable(true);
            }
        });
        save.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                //filter rules save action
                CheckBoxTreeItem cbti = (CheckBoxTreeItem) tree.getFocusModel().getFocusedItem();
                PathNode pn = record.get(cbti);
                pn.setRule(rule.getText());
                pn.setRename(rename.isSelected());
                rule.setEditable(false);
            }
        });
        buttonBox.getChildren().addAll(edit, save);
        rule.setEditable(false);

        rename.selectedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean t1) {

                PathNode pn = record.get(focusItem);
                pn.setRename(t1);
            }
        });
        renameBox.getChildren().addAll(rename);
        renameBox.setPadding(new Insets(10, 10, 0, 0));
        ruleBox.getChildren().addAll(topic, rule, buttonBox, renameBox);
        ruleBox.setPadding(new Insets(10, 10, 10, 10));
        ruleBox.setSpacing(10);
        ruleBox.setPrefWidth(250);
        //ruleBox.setDisable(true);
        setRuleBoxStatus(false);
        renameBox.setDisable(true);

        BorderPane treePane=new BorderPane();
        treePane.setCenter(tree);
        treePane.setRight(ruleBox);

        BorderPane root=new BorderPane();
        root.setCenter(treePane);
        HBox hbox=new HBox();

        final ToggleGroup group=new ToggleGroup();
        selectAll.setToggleGroup(group);

        selectAll.setUserData("1");
        deselectAll.setToggleGroup(group);

        deselectAll.setUserData("0");
        group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> observableValue, Toggle toggle, Toggle t1) {
                if(group.getSelectedToggle()!=null){
                    //select all
                    if(group.getSelectedToggle().getUserData().equals("0")){
                        rootItem.setSelected(false);
                    }
                    //deselect all
                    else{
                        rootItem.setSelected(true);
                    }
                }
            }
        });
        //start downloading, policy should contains all of directory and supported file type you need
        download.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                InterfaceDataManagerHttp.getPathNode(policy,downloadto.getText());
//                for(PathNode pn:policy){
//                    System.out.println("PathNode: " + pn.getPath() + ", policy: " + pn.getRule() + ",rename? " + pn.isRename());
//                }
                close();
            }
        });
        cancel.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                close();
                //shutDown();
            }
        });
        HBox downloadpath=new HBox();
        downloadpath.setPrefHeight(40);
        downloadpath.setAlignment(Pos.CENTER);
        downloadpath.getChildren().addAll(dltoLabel,downloadto);
        hbox.getChildren().addAll(selectAll, deselectAll,downloadpath, download);
        hbox.setPrefHeight(40);
        hbox.setAlignment(Pos.CENTER);
        hbox.setSpacing(50);
        root.setBottom(hbox);

        setScene(new Scene(root, 800,600));

    }

//    public void createTree(CheckBoxTreeItem<String> cbti,PathNode pn){
//
//        cbti.setValue(pn.getPath().substring(pn.getPath().lastIndexOf("/")+1));
//        for(PathNode pathNode: pn.getChilds()){
//
//            final CheckBoxTreeItem<String> treeItem = new CheckBoxTreeItem<String> (pathNode.getPath().substring(pathNode.getPath().lastIndexOf("/")+1));
//            treeItem.selectedProperty().addListener(new ChangeListener<Boolean>() {
//                @Override
//                public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean t1) {
//
//                    if(t1&&!aBoolean){
//                        if(!policy.contains(record.get(treeItem))){
//                            policy.add(record.get(treeItem));
//                        }
//                    }
//                    if(!t1&&aBoolean){
//                        if(policy.contains(record.get(treeItem))){
//                            policy.remove(record.get(treeItem));
//                        }
//                    }
//                }
//            });
//            record.put(treeItem,pathNode);
//            cbti.getChildren().add((treeItem));
//            createTree(treeItem, pathNode);
//        }
//
//    }

    public void createTree(CheckBoxTreeItem<String> cbti,PathNode pn){

        if(pn.getPath().endsWith("/")){
            pn.setPath(pn.getPath().substring(0,pn.getPath().lastIndexOf("/")));
        }
        cbti.setValue(pn.getPath().substring(pn.getPath().lastIndexOf("/")+1));
        for(PathNode pathNode: pn.getChilds()){
            String pnName=pn.getPath().substring(pn.getPath().lastIndexOf("/")+1);
            if(pnName.equals("trans")){
                final CheckBoxTreeItem<String> treeItem = new CheckBoxTreeItem<String> (pathNode.getPath().substring(pathNode.getPath().lastIndexOf("/")+1));
                treeItem.selectedProperty().addListener(new ChangeListener<Boolean>() {
                    @Override
                    public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean t1) {

                        if(t1&&!aBoolean){
                            if(!policy.contains(record.get(treeItem))){
                                policy.add(record.get(treeItem));
                            }
                        }
                        if(!t1&&aBoolean){
                            if(policy.contains(record.get(treeItem))){
                                policy.remove(record.get(treeItem));
                            }
                        }
                    }
                });
                record.put(treeItem,pathNode);
                cbti.getChildren().add((treeItem));
                createTree(treeItem, pathNode);
            }
        }
    }


    public void setRuleBoxStatus(boolean status){

        topic.setDisable(!status);
        rule.setDisable(!status);
        edit.setDisable(!status);
        save.setDisable(!status);
    }

    public void shutDown(){

        try {
            Platform.exit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取文件结构
    private String getjsonFromUrl(String url)
    {
        HttpURLConnection connection = null;
        Reader reader= null;
        try {
            URL urlobject = new URL(url);

            connection = (HttpURLConnection) urlobject.openConnection();
            //connection.setSSLSocketFactory(HttpsDefault.getSSLSocketFactory());

            connection.connect();
            InputStream inputStream = connection.getInputStream();
            //对应的字符编码转换
            reader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            StringBuffer sb = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        finally {
            try {
                if (connection != null)
                    connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }



}
